import {ReactElement} from 'react'
import { awaitWrap, confirmAction, formatDate } from '@src/assets/js/tool'
import { PerformanceSchema } from '@src/components/schema/performanceSchema'
import { addWindow } from '@src/redux/actions/tab'
import { Space, Divider, message, Dropdown, Menu } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { Dispatch } from 'redux'
import { setPerformanceUnable } from './ajax'
import style from './index.module.less'
import {DownOutlined} from '@ant-design/icons'

async function setDsiable (id: string, refreshFn: () => void): Promise<void> {
  const hide = message.loading('提交中', 60)
  const [e] = await awaitWrap(setPerformanceUnable(id))
  hide()
  if (e !== null) {
    message.warning(e.message).then(null, null)
  } else {
    message.success('作废成功').then(null, null)
    refreshFn()
  }
}

function renderMenu (data: PerformanceSchema, dispatch: Dispatch, refreshFn: () => void): ReactElement {
  const {id} = data
  return (
    <Menu items={[
      {label: '案件列表', key: 1, onClick: () => {
        dispatch(addWindow({ id: `performance-case-list-${id}`, title: `${data.title}-案件列表`, componentName: 'PerformanceCaseList', meta: { id } }))
      }},
      {label: '绩效评价', key: 2, onClick: () => {
        dispatch(addWindow({ id: `work-performance-${id}`, title: `${data.title}-绩效评价`, componentName: 'WorkPerformance', meta: {id} }))
      }},
      {label: '全委绩效', key: 3, onClick: () => {
        dispatch(addWindow({ id: `work-total-performance-${id}`, title: `${data.title}-全委绩效`, componentName: 'TotalWorkPerformance', meta: {id} }))
      }},
      {label: '作废', key: 4, onClick: () => {
        confirmAction('作废后数据将无法显示！确认是否作废本次绩效考核？', async () => {
          await setDsiable(id, refreshFn)
        })
      }},
    ]}>
    </Menu>
  )
}

export function getColumn (dispatch: Dispatch, setVisible: (v: boolean) => void, setModifyData: (v: PerformanceSchema) => void, refreshFn: () => void): ColumnsType<PerformanceSchema> {
  const columns: ColumnsType<PerformanceSchema> = [
    {
      title: '序号',
      dataIndex: 'orderno',
      key: 'orderno',
      width: 80
    },
    {
      title: '考核名称',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '考核进度',
      dataIndex: 'status',
      key: 'status'
    },
    {
      title: '受理考核（人/均值总分/去年同期）',
      dataIndex: 'accept',
      key: 'accept',
      render: (v, l: PerformanceSchema) => {
        const num: number = typeof l.accepter_num === 'number' ? l.accepter_num : 0
        const score: string = typeof l.accepter_ratio_score_avg === 'number' ? l.accepter_ratio_score_avg.toFixed(3) : '0'
        const otherScore: string = typeof l.pre_accepter_ratio_score === 'number' ? l.pre_accepter_ratio_score.toFixed(3) : '0'
        return `${num} / ${score} / ${otherScore}`
      }
    },
    {
      title: '办案考核（人/均值总分/去年同期）',
      dataIndex: 'process',
      key: 'process',
      render: (v, l: PerformanceSchema) => {
        const num: number = typeof l.processer_num === 'number' ? l.processer_num : 0
        const score: string = typeof l.processer_ratio_score_avg === 'number' ? l.processer_ratio_score_avg.toFixed(3) : '0'
        const otherScore: string = typeof l.pre_processer_ratio_score === 'number' ? l.pre_processer_ratio_score.toFixed(3) : '0'
        return `${num} / ${score} / ${otherScore}`
      }
    },
    {
      title: '非办案考核（人/平均分）',
      dataIndex: 'work',
      key: 'work',
      render: (v, l: PerformanceSchema) => {
        const num: number = typeof l.work_num === 'number' ? l.work_num : 0
        const score: string = typeof l.work_average_score === 'number' ? l.work_average_score.toFixed(3) : '0'
        return `${num} / ${score}`
      }
    },
    {
      title: '考核时间',
      dataIndex: 'begin_datetime',
      key: 'begin_datetime',
      render: (v: number, l: PerformanceSchema) => {
        if (typeof l.begin_datetime === 'number' && typeof l.end_datetime === 'number') {
          const begin = formatDate(l.begin_datetime, 'YYYY年MM月DD日')
          const end = formatDate(l.end_datetime, 'YYYY年MM月DD日')
          return `${begin}至${end}`
        }
        return <span />
      }
    },
    {
      title: '负责人',
      dataIndex: 'principal',
      key: 'principal'
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      render: (v: string, l: PerformanceSchema) => {
        return (
          <Space size='middle'>
            <a className={style['operate-btn']} onClick={() => { setModifyData(l); setVisible(true) }}>编辑</a>
            <Dropdown overlay={renderMenu(l, dispatch, refreshFn)} trigger={['click']}>
              <a className={style.more}>
                <span>更多</span>
                <DownOutlined/>
              </a>
            </Dropdown>
          </Space>
        )
      }
    }
  ]
  return columns
}
